package com.koko.controller;

import com.koko.constant.MessageConstant;
import com.koko.context.BaseContext;
import com.koko.exception.UserAlreadyHavaTheGameException;
import com.koko.result.Result;
import com.koko.service.UserGameService;
import com.koko.user.entity.UserGame;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/user")
public class UserGameController {
    @Autowired
    private UserGameService userGameService;

    /**
     * feign接口，判断用户是否拥有此游戏
     * @param gameId
     * @param userId
     * @return
     */
    @GetMapping("/game/ishave")
    public String isUserHaveGameOrNot(@RequestParam Long gameId, @RequestParam Long userId) {
        return userGameService.isUserHaveGame(userId, gameId);
    }

    /**
     * 将游戏添加给用户
     * @param user
     * @return
     */
    @PostMapping("/game")
    public Result<String> addGameToUser(@RequestBody UserGame user) {
        String nickname = userGameService.isUserHaveGame(BaseContext.getCurrentId(), user.getGameId());
        // 判断用户是否拥有此游戏
        if (nickname != null) {
            String message = "您" + MessageConstant.ALREADY_HAVE_THE_GAME;
            throw new UserAlreadyHavaTheGameException(message);
        }
        // 没有则封装数据
        UserGame userGame = new UserGame();
        // 2. 封装数据
        userGame.setUserId(BaseContext.getCurrentId());
        userGame.setGameId(user.getGameId());
        userGame.setCreateTime(LocalDateTime.now());
        userGameService.addGameForUser(userGame);
        return Result.success();
    }
}
